package net.alpcontrol.bi.bootstrap.exception;

import net.alpcontrol.bi.bootstrap.bean.Message;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class AlpExceptionHandler
{
  @ExceptionHandler({MethodArgumentNotValidException.class})
  @ResponseBody
  public Message exceptionHandler(MethodArgumentNotValidException ex)
  {
    List errors = ex.getBindingResult().getAllErrors();
    if (errors.size() > 0) {
      return Message.failure(((ObjectError)errors.get(0)).getDefaultMessage());
    }
    return Message.failure("无效的参数");
  }
  @ExceptionHandler({HttpMessageNotReadableException.class})
  @ResponseBody
  public Message exceptionHandler(HttpMessageNotReadableException ex) {
    return Message.failure("参数不能为空");
  }
  @ExceptionHandler({HttpMediaTypeNotSupportedException.class})
  @ResponseBody
  public Message exceptionHandler(HttpMediaTypeNotSupportedException ex) { return Message.failure("不支持的内容类型"); }
  @ExceptionHandler({AlpException.class})
  @ResponseBody
  public Message exceptionHandler(AlpException ex) {
    return Message.failure(ex.getCode(), ex.getMessage(), null);
  }
  @ExceptionHandler({Exception.class})
  @ResponseBody
  public Message exceptionHandler(Exception ex) { ex.printStackTrace();
    return Message.failure(ex.getMessage());
  }
}